package com.mfrs.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;

public class ImageHelper {	
	private static String TAG = "ImageHelper";
	
	public static byte[] getTransferrableBmpBytesFromFile(File f){
		int quality = 100;
		byte[] data = null;
		if(f.exists()){
			try{				
				while(true && quality >= 20 ){					
					data = getCompressJpgBytes(f, quality);					
					if(data == null)
						break; //Wrong image file type
					int size = data.length / 1024;
					Log.i(TAG, "Size after resizing: " + String.valueOf(size)+ "KB");
					if(size < 1000)
						break;
					else
						quality-= 20;
				}
				if(quality < 30){
					Log.w(TAG, "Quality too low to execute");
				}
			}
			catch(Exception e){
				Log.e(TAG, e.toString());	
			}
		}
		return data;
	}
	
	private static byte[] getCompressJpgBytes(File f, int quality){
		byte[] data = null;		
		Bitmap resultBmp = null;
		try {
			data = FileUtils.readFileToByteArray(f);
			if(data!=null){				
				resultBmp = BitmapFactory.decodeByteArray(data, 0, data.length);
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				resultBmp.compress(CompressFormat.JPEG, quality, stream);				
				data = stream.toByteArray();				
				stream.close();
				resultBmp.recycle();
			}
		} catch (IOException e) {			
			Log.e(TAG, e.toString());		
		}
		return data;
	}
	
	public static Bitmap loadBmpFromData(byte[] data){
		Bitmap result = null;
		try{
			result = BitmapFactory.decodeByteArray(data, 0, data.length);
		}
		catch(Exception e){
			Log.e(TAG, e.toString());
		}
		return result;
	}
}
